<script setup>
    import { ref, reactive, watch, toRaw } from 'vue'
    import { useVModel } from '@vueuse/core'
    import { Form, message } from 'ant-design-vue'
    import defaultSetting from "../../../common/utils/defaultSetting";
    import utils from "../../../common/utils/utils"
    import _ from 'lodash'
    import {
        PlusOutlined
    } from "@ant-design/icons-vue"

    const useForm = Form.useForm;
    const props = defineProps({
        list: {
            type: Array,
            default: () => {
                return []
            }
        },
        limit: {
            type: Number,
            default: 3
        }
    })

    const emit = defineEmits(['update:list'])
    const shortcuts = useVModel(props, 'list', emit)
    const columns = [
        {
          title: "关键词",
          align: "left",
          width: "50%",
          dataIndex: "title",
          key: 'title',
        },
        {
          title: "回复内容",
          align: "left",
          width: "25%",
          slots: {
            customRender: "response",
          },
        },
        {
          title: "操作",
          slots: {
            customRender: "action",
          },
          width: "25%",
          align: "center",
        }
    ]
    const visible = ref(false)
    const editIndex = ref(false)
    
    const modelRef = reactive({
        title: '',
        response: '',
        images: []
    })

    const imageList = ref([])

    const rulesRef = reactive({
        title: [
            {
                required: true,
                message: '请输入关键词',
            },
            {
                min: 2,
                message: '关键词最短不少于 2 个字符',
            },
            {
                max: 10,
                message: '关键词最长不超过 10 个字符',
            }
        ],
        response: [
            {
                required: true,
                message: '请输入回复内容',
            }
        ]
    })

    const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef);

    const baseUrl = `${
      utils.isEnv()
        ? `http://localhost:${location.port}`
        : defaultSetting.requestDomain
    }`;

    const onConfirm = () => {
        validate().then(() => {
            if (editIndex.value !== false) {
                shortcuts.value[editIndex.value] = _.cloneDeep(toRaw(modelRef))
            } else {
                shortcuts.value.push(_.cloneDeep(toRaw(modelRef)))
            }
            emit('change', shortcuts.value)
            visible.value = false
        })
    }

    const onEditClick = (index) => {
        const record = shortcuts.value[index]
        editIndex.value = index
        visible.value = true

        modelRef.title = record.title
        modelRef.response = record.response
        modelRef.images = record.images

        imageList.value = record.images.map((item) => {
            return {
                uid: 1,
                name: item,
                status: "done",
                url: item,
            }
        })
    }

    const onDelClick = (index) => {
        shortcuts.value.splice(index, 1)
        emit('change', shortcuts.value)
    }

    const handleImageUpload = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList.map((file, index) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
            } else {
              message.warning(file.response.msg);
              resFileList.splice(index, 1);
            }
          }
        });
      }
      
      imageList.value = resFileList

      if (resFileList.length) {
        modelRef.images = resFileList.map((item) => item.url)
      } else {
        modelRef.images = []
      }
    }

    watch(visible, (val) => {
        if (! val) {
            resetFields()
            modelRef.images = []
            imageList.value = []
        }
    })

</script>

<template>
    <div>
        <a-table
            :dataSource="shortcuts"
            :columns="columns"
            :pagination="false"
            rowKey="id"
            :bordered="true"
            size="small"
          >
            <template #response="{ record }">
                {{ record.images.length > 0 ? '文字 + 图片' : '文字' }}
            </template>
            <template #action="{ index }">
              <a-button
                type="link"
                style="padding: 0; margin: 0"
                @click="onEditClick(index)"
                >编辑</a-button
              >
              <a-button
                type="link"
                style="padding: 0; margin-left: 5px"
                @click="onDelClick(index)"
                >删除</a-button
              >
            </template>
          </a-table>
        <div v-if="shortcuts.length < limit" class="mt-10">
            <a-button
                size="small"
                style="border-radius: 6px"
                @click="visible = true"
                ><PlusOutlined />添加菜单栏</a-button
            >
        </div>

        <a-modal v-model:visible="visible" :title="`${editIndex ? '编辑' : '添加'}菜单栏`" width="600px" @ok="onConfirm">
            <a-form layout="vertical">
                <a-form-item label="关键词" v-bind="validateInfos.title">
                    <a-input v-model:value="modelRef.title" placeholder="输入关键词"/>
                </a-form-item>
                <a-form-item label="回复内容" v-bind="validateInfos.response">
                    <a-textarea v-model:value="modelRef.response" :rows="4" :placeholder="`输入回复内容。如需网页链接跳转，请直接填写域名，例如: ${baseUrl}`" :maxlength="3000" show-count/>
                </a-form-item>
                <a-form-item label="图片（最多上传9张）">
                    <a-upload
                    :action="$utils.imgAction"
                    :headers="{ 'org-token': $store.getters.token }"
                    v-model:file-list="imageList"
                    @change="handleImageUpload"
                    :multiple="true"
                    name="image"
                    :data="{ dir: 'work_ai' }"
                    accept="image/*"
                    list-type="picture-card"
                  >
                    <div v-if="imageList.length < 9">
                      <PlusOutlined />
                      <div>上传图片</div>
                    </div>
                  </a-upload>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<style lang="less" scoped>

</style>